/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javafeiq.service.detect.util.impl;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafeiq.service.detect.ClientDetectUtil;
import javafeiq.service.detect.util.DetectService;
import javafeiq.service.status.StatusConstant;

/**
 *
 * @author bitray
 */
public class UdpDetect implements DetectService {

    @Override
    public boolean isConnect(String ip) {
        boolean t = false;
        DatagramSocket datagramSocket = null;
        try {
            datagramSocket = new DatagramSocket();
            datagramSocket.connect(InetAddress.getByName(ip), StatusConstant.DEFAULT_PORT);
            t = datagramSocket.isConnected();
            System.out.println(t);
        } catch (SocketException ex) {
            Logger.getLogger(ClientDetectUtil.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnknownHostException ex) {
            Logger.getLogger(ClientDetectUtil.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (datagramSocket != null) {
                datagramSocket.disconnect();
                datagramSocket.close();
            }
        }
        return t;
    }

    @Override
    public boolean sendInfo(String ip, String info) {
        boolean t = false;
        DatagramSocket datagramSocket = null;
        try {
            datagramSocket = new DatagramSocket();
            DatagramPacket datagramPacket = new DatagramPacket(info.getBytes(), info.getBytes().length, InetAddress.getByName(ip), StatusConstant.DEFAULT_PORT);
            datagramSocket.send(datagramPacket);
            t = true;
        } catch (SocketException ex) {
            Logger.getLogger(ClientDetectUtil.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnknownHostException ex) {
            Logger.getLogger(ClientDetectUtil.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ClientDetectUtil.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (datagramSocket != null) {
                datagramSocket.close();
            }
        }
        return t;
    }
}
